using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty.AI
{
    [CustomEditor(typeof(BodyRenderController))]
    public class BodyRenderControllerEditor : UnityEditor.Editor
    {
        // 自身组件
        private BodyRenderController _Target;

        private GameObject _BodyPart;
    
        void OnEnable()
        {
            _Target = this.target as BodyRenderController;
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();
        
            if (GUILayout.Button("存储骨骼信息", new GUIStyle("AC Button")))
            {
                Transform boneRoot = _Target.transform.Find("Root");
                if (boneRoot)
                {
                    List<BodyRenderController.BoneData> bones = new List<BodyRenderController.BoneData>();
                    TraverseBoneNode(boneRoot, bones);
                    _Target.bones = bones;
                    _Target.rootBone = boneRoot;
                    
                    EditorUtility.SetDirty(_Target);
                    AssetDatabase.Refresh();
                    AssetDatabase.SaveAssets();
                }
            }
            
            GUILayout.Space(30);
            GUILayout.Label("编辑器下测试:");
            
            _BodyPart = EditorGUILayout.ObjectField("部位模型", _BodyPart, typeof(GameObject), false) as GameObject;
            if (GUILayout.Button("新增部位预览", new GUIStyle("AC Button")))
            {
                if (_BodyPart)
                {
                    _Target.InitBonesMap();
                    GameObject go = Instantiate(_BodyPart);
                    _Target.AddBodyPart(go.transform);
                }
            }
        

        }

        /// <summary>
        /// 遍历输出骨骼点
        /// </summary>
        /// <param name="node"></param>
        /// <param name="bones"></param>
        void TraverseBoneNode(Transform node, List<BodyRenderController.BoneData> bones)
        {
            foreach (var data in bones)
            {
                if (data.name == node.name)
                {
                    Debug.LogError("骨骼名字重复: " + data.name);
                }
            }
            
            BodyRenderController.BoneData boneData = new BodyRenderController.BoneData();
            boneData.name = node.name;
            boneData.bone = node;
            bones.Add(boneData);
            
            foreach (Transform child in node)
            {
                TraverseBoneNode(child, bones);    
            }
        }
    
    }   
}
